package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Slf4j
@Component
public class AutoFillAspect {
    //为了提高扫描效率，可以指定扫描某个包
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut(){}

    /**
     * 前置通知，在执行insert或者update之前，给参数赋值
     * @param joinPoint
     */
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) throws Exception {
        log.info("开始进行自动填充：");
        //获得方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获得方法上的注解
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();
        //获得方法参数
        Object[] args = joinPoint.getArgs();
        if (args==null || args.length==0){
            return;
        }
        Object arg = args[0];
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();
        //新增
        if (operationType==OperationType.INSERT){
            Method setCreateTime = arg.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
            Method setUpdateTime = arg.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
            Method setCreateUser = arg.getClass().getDeclaredMethod("setCreateUser", Long.class);
            Method setUpdateUser = arg.getClass().getDeclaredMethod("setUpdateUser", Long.class);

            setCreateTime.invoke(arg,now);
            setUpdateTime.invoke(arg,now);
            setCreateUser.invoke(arg,currentId);
            setUpdateUser.invoke(arg,currentId);
        }
        //修改
        if (operationType==OperationType.UPDATE){
            Method setUpdateTime = arg.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
            Method setUpdateUser = arg.getClass().getDeclaredMethod("setUpdateUser", Long.class);

            setUpdateTime.invoke(arg,now);
            setUpdateUser.invoke(arg,currentId);
        }

    }
}



















